package cn.iocoder.yudao.module.system.framework.translate.core.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.system.framework.translate.config.TranslateConfig;
import cn.iocoder.yudao.module.system.framework.translate.core.ITranslateClient;
import cn.iocoder.yudao.module.system.framework.translate.model.GoogleTranslationResponse;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * https://juejin.cn/s/google%20translate%20api%20free%20java
 * Description: 谷歌翻译实现
 * Author: li
 * Date: 2024/2/20
 */
@Slf4j
@Component
public class GoogleTranslateClientImpl implements ITranslateClient {
    private static final String BASE_URL = "https://translation.googleapis.com/language/translate/v2";
    @Resource
    private TranslateConfig translateConfig;

    @Override
    public String translate(String text, String targetLanguage) {
        try {
            final String apiKey = translateConfig.getGoogle().getApiKey();
            final String url = BASE_URL + "?key=" + apiKey;

            final Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("q", text);
            paramMap.put("target", targetLanguage);

            final HttpRequest request = HttpRequest.post(url)
                    .form(paramMap)//表单内容
                    .setReadTimeout(30 * 1000);

            final String proxyHost = translateConfig.getProxyHost();
            final Integer proxyPort = translateConfig.getProxyPort();
            if (StringUtil.isNotEmpty(proxyHost)) {
                // 设置代理
                request.setHttpProxy(proxyHost, proxyPort);
            }

            final HttpResponse response = request.execute();
            final int statusCode = response.getStatus();
            final String jsonResponse = response.body();
            log.info("翻译文本, statusCode = {}, targetLanguage = {}, text = {}, resp = {}",
                    statusCode, targetLanguage, text, jsonResponse);

            if (response.isOk()) {
                final String translatedText = extractTranslatedText(jsonResponse);
                return translatedText;
            } else {
                throw new RuntimeException(String.format("翻译文本失败, statusCode = %s", statusCode));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String extractTranslatedText(String jsonResponse) {
        final GoogleTranslationResponse response = JsonUtils.parseObject(jsonResponse, GoogleTranslationResponse.class);
        final GoogleTranslationResponse.Data data = response.getData();
        final List<GoogleTranslationResponse.Translation> translations = data.getTranslations();
        final GoogleTranslationResponse.Translation translation = translations.get(0);
        final String translatedText = translation.getTranslatedText();
        return translatedText;
    }

    public static void main(String[] args) throws Exception {
        final GoogleTranslateClientImpl impl = new GoogleTranslateClientImpl();
        impl.translateConfig = new TranslateConfig();
//        impl.translateConfig.setProxyHost("127.0.0.1");
//        impl.translateConfig.setProxyPort(7078);
        impl.translateConfig.setGoogle(new TranslateConfig.Google("AIzaSyDXoOSwSDLICngWBxWXYQITh0yP2rZkN50"));

        final String text = "今日特价";
        final String translatedText = impl.translate(text, "en");
        System.out.println(translatedText);
    }

}
